package syncagent.impl;

import java.net.URI;
import java.util.Calendar;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.osgi.service.event.Event;

import syncagent.RemoteEvent;
import syncagent.SyncAgent;
import syncagent.SyncAgentService;

public class SyncAgentServiceImpl implements SyncAgentService {
		private SyncAgent agent;
		private String ID;
		
		public SyncAgentServiceImpl(SyncAgent syncAgent) {
			agent = syncAgent;
			// create a java calendar instance
			Calendar calendar = Calendar.getInstance();

			// get a java.util.Date from the calendar instance.
			// this date will represent the current instant, or "now".
			java.util.Date now = calendar.getTime();
			ID = now.toString();

		}

		public String sayHello() {
			return "Hello World!! ";
		}

		public String sayGoodbye() {
			return "Goodbye World!!";
		}

		public void callHome(URI homeAddress) {
			// TODO Auto-generated method stub
			
		}

		public void pushEvents(Event events) {
			String[] params = events.getPropertyNames();
			Dictionary result = new Hashtable();  
			
			for(int i = 0; i < params.length; i++)
			{
				result.put(params[i], events.getProperty(params[i]));  
			}
			RemoteEvent pEvent = new RemoteEvent(events.getTopic(), result);
			
			Map<SyncAgentService, String> agents = agent.getClients();
			
			for (Iterator<Entry<SyncAgentService, String>> it = agents.entrySet().iterator(); it.hasNext(); ) {
                Entry<SyncAgentService, String> entry = it.next();
                try {
                	System.out.println("Sending an event to remote agent");
                    entry.getKey().publishEvents(pEvent);
                } catch (Throwable th) {
                    System.out.println("Could not send message to display: " + entry.getValue());
                }
            }
		}

		public String getID() {
			return ID;
		}

		public void publishEvents(Event event) {
			
		}

		public void publishEvents(RemoteEvent event) {
			System.out.println("Received an event!");
			
		}

}
